#include <deque>
#include <iostream>
using namespace std;
class Solution {
public:
  int monotoneIncreasingDigits(int n) {
      if(n == 0) return 0;
    deque<int> temp;
    int tempint = n;
    while (tempint != 0) {
      temp.push_front(tempint % 10);
      tempint = tempint / 10;
    }

    for (int i = 0; i < temp.size() - 1; ++i) {
      if (temp[i] > temp[i + 1]) {
        temp[i + 1] = 9;
        --temp[i];
        for (int j = i - 1; j >= 0; --j) {
          if (temp[j] > temp[j + 1]) {
            --temp[j];
            temp[j + 1] = 9;
          } else {
            break;
          }
        }
        for (int j = i + 1; j < temp.size(); ++j) {
          temp[j] = 9;
        }
        break;
      }
    }
    int res = 0;
    while (!temp.empty()) {
      res = res * 10 + temp.front();
      temp.pop_front();
    }
    return res;
  }
};

int main(int argc, char *argv[]) {
  cout << Solution().monotoneIncreasingDigits(332);
  return 0;
}
